package com.gopay.scheduler.service.entrustpay.impl;

import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import com.gopay.common.order.dao.CommonQueryDAO;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Service;

import com.gopay.common.constants.trans.AccountingPoint;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.scheduler.dao.CpsGenMainOrderReadDao;
import com.gopay.scheduler.service.entrustpay.EntrustPayService;

/** 
 * @ClassName: EntrustPayServiceImpl 
 * @Description: 委托代收交易Service实现类
 * @author  lx
 * @date 2016年12月31日 下午10:21:16  
 */ 
@Service(value="entrustPayService")
public class EntrustPayServiceImpl implements EntrustPayService{
    @Resource(name="cpsGenMainOrderReadDao")
    CpsGenMainOrderReadDao cpsGenMainOrderReadDao;

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;
    /**
     * 12 小时 （720 分钟）
     */
    public static final int HOUR_12 = 60*12;
    /**
     * 2 天 换算为分钟
     */
    public static final int DAY_2 = 2*24*60;
    /**
     * 1 小时 （60分钟）
     */
    public static final int HOUR_1 = 60;
    public static final int MIN_15=15;
    @Override
    public List<CpsGenMainOrder> getEntrustPayList(String gopayIntTxnCd, int txnStaCd, Date createdTs) {
        DetachedCriteria criteria = DetachedCriteria.forClass(CpsGenMainOrder.class);
        criteria.add(Restrictions.eq("gopayIntTxnCd", gopayIntTxnCd));
        criteria.add(Restrictions.eq("txnStaCd", txnStaCd));
        criteria.add(Restrictions.eq("accountPoint", AccountingPoint._00666_DEFAULT.value));
        criteria.add(Restrictions.le("gopayTxnTm", createdTs));
        //两周 （14天内）的 30102交易可以 做账 超过 2周 即便是 30102 也不再处理
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(createdTs);
        calendar.add(Calendar.DAY_OF_MONTH, -14);
        Date before = calendar.getTime(); 
        criteria.add(Restrictions.ge("gopayTxnTm", before));
        
        return cpsGenMainOrderReadDao.findByCriteria(criteria);
    }
    
    @Override
	public List<CpsGenMainOrder> getEntrustPayTimeoutOrderList() {
    	
		 DetachedCriteria criteria = DetachedCriteria.forClass(CpsGenMainOrder.class);
	        criteria.add(Restrictions.eq("gopayIntTxnCd", IntTxnCd._00666.value));
	        criteria.add(Restrictions.eq("txnStaCd", TxnStaCode.TXN_STA_CD_30101.value));
	        Date date = new Date();
	        
	        Calendar calendar = Calendar.getInstance();
	        calendar.setTime(date);
	        calendar.add(Calendar.MINUTE, -HOUR_12);
	        Date before = calendar.getTime();//订单超过12小时 订单仍处于 30101 状态
	        
	        Calendar calendarAfter = Calendar.getInstance();
	        calendarAfter.setTime(date);
	        calendarAfter.add(Calendar.MINUTE, -DAY_2);
	        Date after = calendarAfter.getTime();//订单超过48小时 订单仍处于 30101 状态
	        criteria.add(Restrictions.le("gopayTxnTm", before));
	        criteria.add(Restrictions.ge("gopayTxnTm", after));
	        return cpsGenMainOrderReadDao.findByCriteria(criteria);
	}

    @Override
    public List<CpsGenMainOrder> getEntrustPayFailedOrderList() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        Date dateStartTime = calendar.getTime();
        calendar.add(Calendar.MINUTE, -(HOUR_12));
        Date dateEndTime = calendar.getTime();
        String startTime = sdf.format(dateStartTime);
        String endTime = sdf.format(dateEndTime);
        Map<String, Object> map = new HashMap<>();
        map.put("startTime", startTime);
        map.put("endTime", endTime);

        StringBuffer sb = new StringBuffer();
        //----------委托代收 失败订单 和 网关快捷 api 失败订单处理 sql-------------------
        sb.append(" select t.gopay_order_id,1  ");
        sb.append(" from cps_gen_main_order t left join bis_bank_main_order b ");
        sb.append(" on t.gopay_order_id = b.gopay_order_id  ");
        sb.append(" where t.gopay_int_txn_cd='00666' and t.txn_sta_cd in (30101,90101)  and b.order_status in (91,99) ");//委托代收
        sb.append(" and TO_CHAR(t.gopay_txn_tm, 'YYYY-MM-DD hh24:mi:ss') > :endTime  ");
        sb.append(" and TO_CHAR(t.gopay_txn_tm, 'YYYY-MM-DD hh24:mi:ss') < :startTime ");
        sb.append(" union all ");
        sb.append(" select t.gopay_order_id,1  ");
        sb.append(" from cps_gen_main_order t left join bis_bank_main_order b ");
        sb.append(" on t.gopay_order_id = b.gopay_order_id  ");
        sb.append(" where t.gopay_int_txn_cd='00100' and t.pay_channel in ('30','31')  ");
        sb.append(" and t.txn_sta_cd in (30101,90101)  and b.order_status in (91,99) ");// 00100 快捷api
        sb.append(" and TO_CHAR(t.gopay_txn_tm, 'YYYY-MM-DD hh24:mi:ss') > :endTime  ");
        sb.append(" and TO_CHAR(t.gopay_txn_tm, 'YYYY-MM-DD hh24:mi:ss') < :startTime ");

        List<Object[]> list = commonQueryDAO.findBySql(sb.toString(), map);

        return buildOrderListBySQL(list);
    }
    private List<CpsGenMainOrder> buildOrderListBySQL( List<Object[]> list ){
        List<CpsGenMainOrder> orderList = new ArrayList<>();
        for (Object[] obj : list){
            CpsGenMainOrder order = new CpsGenMainOrder();
            order.setGopayOrderId(obj[0].toString());
            orderList.add(order);
        }
        return  orderList;
    }

}
